<template>
  <div class="ma-content-block lg:flex justify-between">
    <a-spin style="width: 100%;" :loading="spinLoading" tip="导出中">
      <template #tip>
        <div>
          <a-progress :animation="true" :stroke-width="10" track-color="#d3ccd6" width="130" size="large" type="circle"
            status='warning' :percent="percent" />
          <div style="margin-top: 10px;text-align: center;">{{ exportTxt }}</div>
        </div>

      </template>
      <sa-table ref="crudRef" :options="options" :columns="columns" @resetSearch="resetSearch" :searchForm="searchForm">
        <template #expandArea="data" v-if="paramsData.authRes == true || paramsData.authRes == 1">
          <a-descriptions :column="6" title="汇总信息" bordered>
            <a-descriptions-item label="报单品：" :span="3">条数：{{ data.total_data?.vip_num }} 金额：{{
              data.total_data?.vip_price }} NT： {{ data.total_data?.vip_price_nt }}</a-descriptions-item>
            <a-descriptions-item label="兑换品：" :span="3">条数：{{ data.total_data?.common_num }} 金额：{{
              data.total_data?.common_price }} NT： {{ data.total_data?.common_price_nt }}</a-descriptions-item>
            <a-descriptions-item label="二代报单品：" :span="3">条数：{{ data.total_data?.vip2_num }} 金额：{{
              data.total_data?.vip2_price }} NT： {{ data.total_data?.vip2_price_nt }}</a-descriptions-item>
            <a-descriptions-item label="二代兑换品：" :span="3">条数：{{ data.total_data?.common2_num }} 金额：{{
              data.total_data?.common2_price }} NT： {{ data.total_data?.common2_price_nt }}</a-descriptions-item>
            <a-descriptions-item label="辅消品：" :span="3">条数：{{ data.total_data?.fuxiao_num }} 金额：{{
              data.total_data?.fuxiao_price }} NT： {{ data.total_data?.fuxiao_price_nt }}</a-descriptions-item>
            <a-descriptions-item label="礼品卡：" :span="3">条数：{{ data.total_data?.lipinka_num }} 金额：{{
              data.total_data?.lipinka_price }} NT： {{ data.total_data?.lipinka_price_nt }}</a-descriptions-item>

            <a-descriptions-item label="U豆支付" :span="1">金额：{{ data.total_data?.usdt_price }}</a-descriptions-item>
            <a-descriptions-item label="积分支付" :span="2">金额：{{ data.total_data?.points_price }}</a-descriptions-item>
            <a-descriptions-item label="W金支付" :span="2">金额：{{ data.total_data?.usdt2_price }}</a-descriptions-item>
            <a-descriptions-item label="W分支付" :span="1">金额：{{ data.total_data?.points2_price }}</a-descriptions-item>
          </a-descriptions>
          <a-descriptions :column="4" title="" bordered style="margin-top: 10px;margin-bottom: 10px;">
            <a-descriptions-item label="Stripe" :span="1">{{ data.total_pay_log_data?.stripe_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="AirWallex" :span="1">{{ data.total_pay_log_data?.airWallex_text }}
              (美元)</a-descriptions-item>
            <a-descriptions-item label="微信支付" :span="1">{{ data.total_pay_log_data?.wx_text }}(美元)</a-descriptions-item>
            <a-descriptions-item label="支付宝" :span="1">{{ data.total_pay_log_data?.alipay_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="购物积分" :span="1">{{ data.total_pay_log_data?.ugw_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="兑换积分" :span="1">{{ data.total_pay_log_data?.integral_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="U豆" :span="1">{{ data.total_pay_log_data?.usdt_money_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="W分" :span="1">{{ data.total_pay_log_data?.pay_points2_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="W金" :span="1">{{ data.total_pay_log_data?.usdt2_money_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="中国信托" :span="1">{{ data.total_pay_log_data?.btcb_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="礼品卡折扣" :span="1">{{ data.total_pay_log_data?.gift_card_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="快点付" :span="1">{{ data.total_pay_log_data?.kdf_text }}(美元)</a-descriptions-item>
            <a-descriptions-item label="钱海支付" :span="1">{{ data.total_pay_log_data?.oceanpay_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="Payssion" :span="1">{{ data.total_pay_log_data?.payssion_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="台新银行" :span="1">{{ data.total_pay_log_data?.tspg_text
            }}(美元)</a-descriptions-item>
            <a-descriptions-item label="糖果支付" :span="1">{{ data.total_pay_log_data?.utg_text
            }}(美元)</a-descriptions-item>
          </a-descriptions>
        </template>
        <template #tableSearch>
          <a-col :span="6">
            <a-form-item field="order" label="订单信息">
              <a-input v-model="searchForm.order" placeholder="请输入" @keydown.enter="refresh"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="transaction_no" label="交易单号">
              <a-input v-model="searchForm.transaction_no" placeholder="请输入" @keydown.enter="refresh"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="user" label="会员账号">
              <a-input v-model="searchForm.user" placeholder="会员账号" @keydown.enter="refresh"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="uid" label="会员UID">
              <a-input v-model="searchForm.uid" placeholder="会员UID" @keydown.enter="refresh"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="pay_state" label="支付状态">
              <sa-select v-model="searchForm.pay_state" :data="paramsData.pay_state" @change="refresh"></sa-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="order_state" label="订单状态">
              <sa-select v-model="searchForm.order_state" :data="paramsData.order_state" @change="refresh"></sa-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="order_type" label="订单类型">
              <sa-select v-model="searchForm.order_type" :data="paramsData.order_type" @change="refresh"></sa-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="shipping_time" label="发货日期">
              <a-range-picker v-model="searchForm.shipping_time" format="YYYY-MM-DD" :allow-clear="true"
              @change="refresh"></a-range-picker>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="create_time" label="下单时间">
              <a-range-picker v-model="searchForm.create_time" format="YYYY-MM-DD" :allow-clear="true"
              @change="refresh"></a-range-picker>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="date" label="支付时间">
              <a-range-picker v-model="searchForm.date" format="YYYY-MM-DD" :allow-clear="true"
              @change="refresh"></a-range-picker>
            </a-form-item>
          </a-col>
        </template>
        <template #order="{ record }">
          <div>ID: {{ record.id }}</div>
          <div>订单号: {{ record.order_sn }}</div>
          <div>类型: {{ record.order_type_text }}</div>
        </template>
        <template #member="{ record }">
          <div>UID: {{ record.user_id }}</div>
          <div>用户名: {{ record.user_name }}</div>
          <div>真实姓名: {{ record.true_name }}</div>
        </template>
        <template #state="{ record }">
          <div>支付状态: {{ record.pay_state_text }}</div>
          <div>订单状态: {{ record.order_state_text }}</div>
          <div>发货方式: {{ record.GetMethodsText }}</div>
          <div>收货地: {{ record.address ? record?.address?.country : '' }}</div>
          <div>同步wx发货: {{ record.shipping_state_text }}</div>
        </template>
        <template #goods="{ record }">
          <div>附销品: {{ record.fuxiaoText }}</div>
          <div>礼品卡: {{ record.lipinkaText }}</div>
          <div>二代保单品: {{ record.vip2Text }}</div>
          <div>二代兑换品: {{ record.common2Text }}</div>
        </template>
        <template #price="{ record }">
            <div>总价: {{'¥' +record.order_total_cny||0 }}</div>
            <div>{{ record.usdt_text }}</div>
            <div>{{ record.points_text }}</div>
            <div>{{ record.service_fee_msg }}</div>
            <div>使用礼品卡: {{ record.gift_card + '张' }}</div>
        </template>
        <template #time="{ record }">
          <div>下单: {{ record.create_time }}</div>
          <div>支付: {{ record.pay_time }}</div>
          <div>发货: {{ record.shipping_time }}</div>
          <div>收货: {{ record.receive_time }}</div>
        </template>
        <template #pay="{ record }">
          <div v-for="(itm, idx) in record.payLog" :key="idx">
            <div class="over_text">{{ itm.pay_title + ':' + itm.pay_num + ' ( ' + itm.createAt + ' ) ' + itm.other_msg }}
            </div>
          </div>
        </template>
        <template #tableAfterButtons>
          <!-- 兩個导出功能禁用了 -->
          <a-button type="primary" :loading="exportLoading" status="warning" style="padding:0 20px;"
            @click="exportExcel"><icon-share-external />导出</a-button>
        
        </template>
        <!-- <template #tableBeforeButtons> 不做
        <a-button type="outline" v-if="selectRowKey.length>0">提交到台湾ERP開票</a-button>
      </template> -->
        <template #operationBeforeExtend="{ record }">
          <div class="custom_cell">
            <a-button type="primary" size="mini" shape="round" @click="handle('detail', record)">详情</a-button>
            <a-button v-if="record.pay_state == 2 && record.order_state == 0" @click="handle('address', record)"
              type="primary" size="mini" shape="round" class="yellow_color">改收货地址</a-button>
            <a-button v-if="record.area == 0 && record.pay_state == 2" @click="handle('edit', record)" type="primary"
              size="mini" shape="round" class="blue_color">编辑</a-button>
            <a-button v-if="record.order_state>0" @click="handle('express', record)" type="primary"
              size="mini" shape="round" class="green_color">物流信息</a-button>
            <a-button v-if="record.pay_state > 0" @click="handle('pay', record)" type="primary" size="mini"
              shape="round">支付记录</a-button>
              <a-button v-if="(record.pay_state==2 || record.pay_state==3) && record.service_state == 4" @click="handle('refund_record', record)" type="primary" size="mini"
                shape="round">退款记录</a-button>
            <a-button @click="handle('refund', record)"
              v-if="record.refundState == 1 && (record.main_id == 0 || record.order_type != 'lipinka')" type="primary"
              size="mini" shape="round" class="red_color_danger">退款</a-button>
            <a-button v-if="record.pay_state == 0" @click="handle('del', record)" type="primary" size="mini"
              shape="round" class="red_color">刪除</a-button>
              <a-button v-if="record.pay_state == 1 && record.pay_usdt_num<1 && record.pay_usdt2_num<1" @click="handle('cancel', record)" type="primary" size="mini"
              shape="round" class="red_color">取消</a-button>


          </div>
        </template>
      </sa-table>
    </a-spin>
    <!-- 编辑表单 -->
    <edit-form ref="editRef" @success="refresh" />
    <detail ref="detailRef"> </detail>
    <sa-operation @ok="refresh" @cancel="operation.visible = false" :visible="operation.visible" :id="operation.id"
      :api="operation.api" :pwdTxt="'admin_pay_password'" :show_google="false"></sa-operation>
    <change-address ref="addressRef" @success="refresh"></change-address>
    <express ref="expressRef" @success="refresh"></express>
    <pay-record ref="recordRef"></pay-record>
    <refund ref="refundRef" @success="refresh"></refund>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, computed, watch, onBeforeUnmount } from 'vue'
import mallApi from '@/api/system/mall'
import SaTable from '@cps/sa-table/index.vue'
import SaSelect from '@cps/sa-select/index.vue'
import SaOperation from '@cps/sa-operation/index.vue'
import { Message } from '@arco-design/web-vue'
import { throttle } from 'lodash';
import EditForm from './edit.vue'
import detail from './detail.vue'
import changeAddress from './changeAddress.vue';
import express from './express.vue';
import payRecord from './payRecord.vue';
import refund from './refund.vue'
import tool from '@/utils/tool';
const exportTxt = ref('正在导出中，请稍候···')
const exportLoading = ref(false)
const exportLoading2 = ref(false)
const crudRef = ref()
const editRef = ref()
const sendRef = ref()
const addressRef = ref()
const expressRef = ref()
const recordRef = ref()
const refundRef=ref()
const percent = ref(0)
const searchForm = ref({
  order: '',
  transaction_no: '',
  user: '',
  pay_state: 99,
  order_state: 99,
  order_type: 99,
  shipping_time: [],//发货
  create_time: [],//下单
  date: [],//支付
  uid:'',

})
const operation = ref({
  visible: false,
})
const deleteForm = ref({ //刪除 确认彈窗
  id: '',
  pay_password: '',
})
const options = reactive({
  api: mallApi.orderList,//表格数据接口
  operationColumnWidth: 200,//操作欄
  showSearch: true,
  columnAlign: 'left',
  pageSimple: false,//是否展示操作欄有 以及工具欄
  isTreeTable: false,
  add: {//頂部新增按鈕
    show: false,
    auth: ['/core/menu/save'],
    func: async () => {
      editRef.value?.open()
    },
  },
  edit: {//操作欄编辑按鈕
    show: false,
    auth: ['/core/menu/update'],
    func: async (record) => {
      editRef.value?.open('edit', record.id)
      editRef.value?.setFormData(record)
    },
  },
  delete: {//操作欄和頂部刪除按鈕
    show: false,
    auth: ['/core/menu/destroy'],
    func: throttle(async (params) => {
      deleteForm.value.id = params.ids[0]
      const { data } = await infoApi.delInfo(deleteForm.value)
      Message.success(`刪除成功`)
      refresh()
    }, 2000)
  },
  isExpand: false,//展開所有子樹
})
const columns = reactive([
  { title: '订单号', dataIndex: 'order', width: 250 },
  { title: '下单会员', dataIndex: 'member', width: 250 },
  { title: '订单状态', dataIndex: 'state', width: 250 },
  { title: '产品组成', dataIndex: 'goods', width: 250 },
  { title: '价格组成', dataIndex: 'price', width: 250 },
  { title: '时间', dataIndex: 'time', width: 250 },
  { title: '支付记录', dataIndex: 'pay', width: 250 },
])
const resetSearch = () => {
  searchForm.value.shipping_time = []
  searchForm.value.date = []
  searchForm.value.create_time = []
}
const initPage = async () => {

}
const detailRef = ref()
const handle = async (type, record) => {
  if (type == 'detail') {
    detailRef.value?.open(record)
  }else if (type == 'refund') {
    refundRef.value?.open('refund',record)
  } else if (type == 'del') {
    operation.value.api = mallApi.orderDelete
    operation.value.id = record.id
    operation.value.visible = true
  } else if (type == 'address') {
    addressRef.value?.open(record)
  } else if (type == 'edit') {
    editRef.value?.open('edit', record.id)
  } else if (type == 'express') {
    expressRef.value?.open(record.id)
  } else if (type == 'pay') {
    recordRef.value?.open(record)
  } else if (type == 'cancel') {
    operation.value.api = mallApi.mall_order_cancel
    operation.value.id = record.id
    operation.value.visible = true
  } else if (type == 'refund_record') { 
    refundRef.value?.open('refund_record',record)
  }
}
const selectRowKey = ref([])
const getSelectRow = (keys) => {
  selectRowKey.value = keys
}
const refresh = async () => {
  crudRef.value?.refresh()
}
const spinLoading = ref(false)
const intervalId = ref(null)
const exportExcel = throttle(async () => {
  exportLoading.value = true
  const queryParams = new URLSearchParams(searchForm.value).toString();
  const downloadUrl = `${import.meta.env.VITE_APP_BASE_URL}/shop/admin/order/export?${queryParams}`
  window.location.href = downloadUrl
  setTimeout(() => {
    exportLoading.value = false
  }, 1500);
}, 3000)
const paramsData = ref({})
const getParams = async () => {
  const { data } = await mallApi.orderListParams()
  paramsData.value = { ...data }
  paramsData.value.pay_state = tool.toArray_value(data.pay_state)
  paramsData.value.pay_state.unshift({ value: 99, title: '全部' })
  paramsData.value.order_state = tool.simpleTransformArray(data.order_state)
  paramsData.value.order_state.unshift({ value: 99, title: '全部' })
  paramsData.value.order_type = tool.simpleTransformArray(data.order_type)
  paramsData.value.order_type.unshift({ value: 99, title: '全部' })
  console.log('11', paramsData.value);
}
onBeforeUnmount(() => {
  if (intervalId.value) {
    clearInterval(intervalId.value)
    intervalId.value = null
  }
})
onMounted(async () => {
  initPage()
  refresh()
  getParams()
})
</script>

<style scoped>
.icon {
  width: 1em;
}

div {
  font-size: 12px;
  text-align: left;
}

:deep(.arco-spin-mask-icon) {
  top: 20% !important;
}

.custom_cell {
  /* background-color: teal; */
  height: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  gap: 8px;
}
</style>